package cn.anson.jujuapp.services;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import cn.anson.jujuapp.Utils;
import cn.anson.jujuapp.utils.SPUtils;

/**
 * 通过服务开启定位的操作
 */
public class MyService extends Service implements AMapLocationListener{

    private AMapLocationClient       locationClient;
    private AMapLocationClientOption locationOption;

    private ConnectivityManager connectivityManager;
    private NetworkInfo         networkInfo;

    private final String TAG = "MYSERVICE";


    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * 服务的生命有两种。1、绑定的生命周期（onCreate(),onStartCommand(),onDestroy()）；2、没有绑定的生命周期(
     * onCreate(),onBind(),onUnbind(),onDestroy())
     *
     */
    @Override
    public void onCreate() {
        Log.v(TAG, "onCreate");

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //判断locationClient和locationOption是否为空
        if (locationOption != null && locationClient!= null){
            //初始化定位参数
            initLocation();
            //初始化定位参数
            initOption();
            // 设置定位参数
            locationClient.setLocationOption(locationOption);
            //开始定位
            locationClient.startLocation();
        }else{
            //初始化定位的类
            locationClient = new AMapLocationClient(Utils.getContext());
            locationOption = new AMapLocationClientOption();
            //初始化定位参数
            initLocation();
            //初始化定位参数
            initOption();
            //设置定位参数
            locationClient.setLocationOption(locationOption);
            //开始定位
            locationClient.startLocation();
        }

        Log.v(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    private void initLocation() {
        /*
        高德定位的三种模式
        1.低功耗模式
        2.仅设备模式
        3.高精度模式
        通过判断手机的的情况来决定使用那种模式
         */
        //使用ConnectivityManager获取手机的网络连接状态
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo.isConnected()){
            if(networkInfo.getType() == connectivityManager.TYPE_WIFI){
                //网络连接是wifi类型
                Toast.makeText(Utils.getContext(),"网络连接是wifi",Toast.LENGTH_SHORT).show();
            }
        }


        // 设置定位监听
        locationClient.setLocationListener(this);
    }

    /**
     * 初始化定位参数
     */
    private void initOption() {
        // 设置定位模式为低功耗模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        // 设置发起定位请求的时间间隔
        locationOption.setInterval(2000);
        // 设置请求的次数

    }

    /**
     * 定位回调监听，当定位完成后调用此方法
     * @param aMapLocation
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        //保存数据
        if (aMapLocation != null){
            Utils.getLocationStr(aMapLocation);
            //写入数据，
            //省
            SPUtils.putString(Utils.getContext(),"province",aMapLocation.getProvider());
            //城市
            SPUtils.putString(Utils.getContext(),"city",aMapLocation.getCity());
            //区
            SPUtils.putString(Utils.getContext(),"district",aMapLocation.getDistrict());
            Log.v(TAG, aMapLocation.toString());
            Toast.makeText(Utils.getContext(),aMapLocation.getCity(),Toast.LENGTH_SHORT).show();
            //如果定位完成，则销毁服务
            onDestroy();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.v(TAG, "onDestroy");
        //释放资源
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }
}
